
// extract()不在下面的模块中
// import { extract } from "$std/encoding/front_matter.ts";
// posix已废弃：https://deno.land/std@0.224.0/path/mod.ts?s=posix
// import { join } from "$std/path";

// https://github.com/denoland/fresh-blog-example/issues/6
// 参考上面进行手动安装：
// >deno add jsr:@std/front-matter
// >deno add jsr:@std/path
// 安装成功后，再使用下面格式进行引用
import { extract } from "@std/front-matter/any";
import { join } from "@std/path";

const POSTS_DIR = "./posts";

export interface Post {
  slug: string;
  title: string;
  publishedAt: Date;
  content: string;
  snippet: string;
}

export async function getPosts(): Promise<Post[]> {
  const files = Deno.readDir(POSTS_DIR);
  const promises = [];
  for await (const file of files) {
    const slug = file.name.replace(".md", "");
    promises.push(getPost(slug));
  }

  const posts = await Promise.all(promises) as Post[];
  posts.sort((a, b) => b.publishedAt.getTime() - a.publishedAt.getTime());
  return posts;
}

export async function getPost(slug: string):Promise<Post|null> {
    const txt = await Deno.readTextFile(join(POSTS_DIR, `${slug}.md`));
    const {attrs, body} = extract(txt);

    return {
        slug,
        title: attrs.title,
        publishedAt: new Date(attrs.published_at),
        content: body,
        snippet: attrs.snippet,
    };
}
